package com.ant.member.controller;

import com.alibaba.fastjson.JSONObject;
import com.ant.common.utils.ResponseResult;
import com.ant.member.entity.User;
import com.ant.member.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.time.Duration;

@RestController
@RequestMapping("/member")
public class LoginController {

    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    private static int COUNT = 0;

    @PostMapping("/dologin")
    public ResponseResult handlerLogin(@RequestBody JSONObject json){
        User user = userService.getUserById(json.getString("userId"));
        String token = redisTemplate.opsForValue().get("userId");//TODO 根据userId获取session/token信息
        if(StringUtils.isEmpty(token)){ //未登录
            /**
             * 生成token，存储到redis并设置过期时间，返回前端以便使用
             */
            redisTemplate.opsForValue().set("userId", json.getString("userId"), Duration.ofSeconds(5));
            token = "empty:" + COUNT + ":" + json.getString("userId");
            COUNT++;
        }
        ResponseResult responseResult = new ResponseResult();
//        Map<String, Object> map = new HashMap<>();
        user.setToken(token);
        responseResult.setData(user);
        return responseResult;
    }
}
